<template>
  <section>
    <!--工具条-->
    <toolbar :buttonList="buttonList" :searchVisible='false'  @callFunction="callFunction"></toolbar>

    <!--列表 default-expand-all-->
    <el-table
      :data="datalist"
      highlight-current-row
      v-loading="listLoading"
      row-key="id"
      style="width: 100%"
      ref="mytable"
      @row-click="selsChange"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column type="index" width="80"></el-table-column>
      <el-table-column label="菜单/按钮" width="200">
        <template slot-scope="scope">
          <i class="fa" :class="scope.row.icon"></i>
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="菜单名称" width></el-table-column>
      <el-table-column prop="mName" label="API接口" width> </el-table-column>
      <el-table-column prop="sequence" label="Sort" width></el-table-column>
      <el-table-column prop="isButton" label="是否按钮" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="!scope.row.isButton ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.isButton ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="func" label="按钮事件" width></el-table-column>
      <el-table-column prop="isHide" label="是否隐藏" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="!scope.row.isHide ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.isHide ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="iskeepAlive" label="keepAlive" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="!scope.row.iskeepAlive ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.iskeepAlive ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      -->
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar"> </el-col>
    <div style="display: block; margin-bottom: 20px"></div>

    <!--新增界面-->
    <el-dialog
      title="新增"
      :visible.sync="addFormVisible"
      v-model="addFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
        ref="addForm"
      >
        <el-form-item label="菜单类型" prop="menuType" >
          <el-radio-group @change="clkType" v-model="menuType">
            <el-radio :label=1>目录</el-radio>
            <el-radio :label=2>页面</el-radio>
            <el-radio :label=3>按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="菜单名称"
          v-if="menuType == 1 || menuType == 2"
          prop="name"
        >
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="路由地址" v-if="menuType == 2" prop="code">
          <el-input v-model="addForm.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="addForm.description"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="isEnabled">
          <el-select v-model="addForm.isEnabled" placeholder="请选择状态">
            <el-option label="禁用" :value="true"></el-option>
            <el-option label="启用" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sequence">
          <el-input v-model="addForm.sequence" auto-complete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item prop="isButton" label="是否按钮" width sortable>
          <el-switch v-model="addForm.isButton"></el-switch>
        </el-form-item> -->
        <el-form-item
          prop="icon"
          v-if="menuType == 1 || menuType == 2"
          label="功能图标"
        >
          <el-autocomplete
            size="mini"
            ref="icon"
            v-model="addForm.icon"
            :fetch-suggestions="getIcons"
            popper-class="page-select-icon"
            style="width: 100%"
          >
            <template slot-scope="{ item }">
              <i :class="item.value"></i>
            </template>
            <template slot="prepend">
              <i :class="addForm.icon"></i>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="按钮事件" v-if="menuType == 3" prop="func">
          <el-select
            style="width: 400px"
            v-model="addForm.func"
            filterable
            placeholder="选择按钮事件"
          >
            <el-option
              v-for="item in functions"
              :key="item.value"
              :label="item.title"
              :value="item.value"
            >
              <span style="float: left">{{ item.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.value
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="isHide" label="隐藏菜单" width sortable>
          <el-switch v-model="addForm.isHide"></el-switch>
        </el-form-item>
        <el-form-item prop="iskeepAlive" label="keepAlive" width sortable>
          <el-switch v-model="addForm.isKeepAlive"></el-switch>
        </el-form-item>
        <el-form-item label="父级菜单" prop="treePids" width sortable>
          <el-cascader
            placeholder="请选择，支持搜索功能"
            style="width: 400px"
            v-model="treePids"
            :options="menuOptions"
            filterable
            :props="{ checkStrictly: true, expandTrigger: 'hover' }"
          ></el-cascader>
        </el-form-item>

        <el-form-item
          prop="apiId"
          label="API接口"
          v-if="menuType != 1"
          width
          sortable
        >
          <el-select
            filterable
            style="width: 100%"
            v-model="addForm.apiId"
            placeholder="请选择API"
          >
            <el-option :key="'0'" :value="'0'" :label="'无需api'"></el-option>
            <el-option
              v-for="item in apilist"
              :key="item.id"
              :value="item.id"
              :label="item.path"
            >
              <span style="float: left">{{ item.path }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.name
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click.native="saveApiSubmit"
          :loading="addLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from "../../../util/date";
import {
  getMenulist,
  getFunctionAll,
  saveMenu,
  getMenuTree,
  removeMenu,
  GetApiListEnabled,
} from "../../api/api";
import { getButtonList } from "../../promissionRouter";
import Toolbar from "../../components/Toolbar";
import qs from "qs";
import iconCls from "../../../util/icons";
export default {
  components: { Toolbar },
  data() {
    return {
      buttonList: [],
      menuOptions: [],
      functions: [],
      datalist: [],
      apilist: [], //接口api列表
      listLoading: false,
      menuType: 1,
      sels: [], //列表选中列
      treePids: [],
      addDialogFormVisible: false,
      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
      },
      //新增界面数据
      addForm: {
        sequence: 0,
        name: "",
        code: "-",
        description: "",
        icon: "",
        func: "",
        isEnabled: true,
        isButton: false,
        isHide: false,
        iskeepAlive: false,
        pid: "0",
        apiId: "",
        menuPids: "",
      },
      select: {},
    };
  },
  methods: {
    clkType() {
      if (this.menuType == 1) {
        this.addForm.code = "-";
        this.addForm.isButton = false;
      } else if (this.menuType == 2) {
        this.addForm.isButton = false;
        // this.addForm.code = "";
      }
    },
    getIcons: function (query, callback) {
      var filter = (icon) => {
        return icon.value.toLowerCase().indexOf(query.toLowerCase()) != -1;
      };
      callback(query ? iconCls.data.filter(filter) : iconCls.data);
    },
    selsChange: function (row) {
      this.select = row;
      this.$refs.mytable.clearSelection();
      this.$refs.mytable.toggleRowSelection(row);
    },
    callFunction(item) {
      this.filters = {
        name: item.search,
      };
      this[item.Func].apply(this, item);
    },
    //获取用户列表
    getMenus() {
      this.listLoading = true;
      getMenulist().then((res) => {
        this.datalist = JSON.parse(res.Data);
        this.listLoading = false;
      });
    },
    //删除
    remove() {
      var rows = this.$refs.mytable.selection;
      if (rows.length == 0) {
        this.$message({
          message: "请选择要删除的数据！",
          type: "error",
        });
        return;
      }
      var arrayIds = [];
      var arrayNames = [];
      var ids = rows.map((c) => {
        arrayIds.push(c.id);
        arrayNames.push(c.name);
        return c.id;
      });

      this.$confirm("确认删除【" + arrayNames.join(",") + "】记录吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          this.listLoading = true;
          let param = qs.stringify({ ids: ids });
          removeMenu(param).then((res) => {
            this.listLoading = false;
            if (res.data.IsSuccess) {
              this.$message({
                message: res.data.message,
                type: "success",
              });
            } else {
              this.$message({
                message: res.data.message,
                type: "error",
              });
            }
            this.getMenus();
          });
        })
        .catch(() => {});
    },
    //显示编辑界面
    update() {
     
      if (!this.select.hasOwnProperty("id")) {
        this.$message({
          message: "请选择要编辑的一行数据！",
          type: "error",
        });
        return;
      }
      this.initFunction();
      this.addFormVisible = true;
      this.addForm = Object.assign({}, this.select);
      this.menuType=this.addForm.menuType || 1;
      if(this.addForm && this.addForm.menuPids && this.addForm.menuPids!='')
      {
        this.treePids = this.addForm.menuPids.split(",");
      }
    //  this.addForm.insertTime=util.format(this.addForm.insertTime,'yyyy-MM-dd hh:mm:ss');
    },
    //显示新增界面
    insert() {
      this.initFunction();
      this.addFormVisible = true;
      this.addForm = Object.assign({}, {});
      // this.treePids = this.addForm.menuPids.split(",");
    },
    //新增
    saveApiSubmit: function () {
      if (this.menuType == 3) {
        var _func =
          this.functions.find((item) => {
            if (item.value == this.addForm.func) {
              return item;
            }
          }) || null;

        if (!this.addForm.func || _func == null) {
          this.$message({
            message: "请选择事件",
            type: "error",
          });
          return;
        }
        this.addForm.name = _func.title;
        this.addForm.icon = _func.icon;
        this.addForm.isButton=true;
      }
      if (this.menuType == 1) {
        this.addForm.apiId = "0";
        this.addForm.code="-";
      }
      this.addForm.menuType = this.menuType;
      this.$refs.addForm.validate((valid) => {
        if (valid) {
            this.addLoading = true;
          // console.log(this.addForm.pids);
          if (!this.treePids || this.treePids.length == 0) {
            this.$message({
              message: "请选择父级菜单",
              type: "error",
            });
            return;
          }
          this.addForm.pid = this.treePids[this.treePids.length - 1];
          this.addForm.menuPids = this.treePids.join(",");

          let para = Object.assign({}, this.addForm);
         // console.log(para);

//    var _objet={
//     "code": " ",
//     "name": "查询",
//     "isButton": true,
//     "isHide": false,
//     "iskeepAlive": false,
//     "func": "search",
//     "icon": "el-icon-search",
//     "description": "查询 接口",
//     "isEnabled": true,
//     "pid": "6",
//     "menuType": 3,
//     "apiId": "13",
//     "menuPids": "0,5,6",
//     "label": "查询",
//     "pnameArr": [],
//     "pCodeArr": [],
//     "mName": "/api/module/get",
//     "mmmm": false,
//     "buttons": null,
//     "sequence": 0,
//     "id": "20",
//     "insertTime":"2019-01-01 00:00:00" ,
//     "updateTime": "2019-01-01 00:00:00"
// };
if(para.insertTime){
para.insertTime=this.$moment( para.insertTime).format('YYYY-MM-DD');
para.updateTime=this.$moment( para.updateTime).format('YYYY-MM-DD');
}

          saveMenu(para).then((res) => {
            if (util.isEmt.format(res)) {
              this.addLoading = false;
              return;
            }
            this.addLoading = false;
            if (res.data.IsSuccess) {
              this.addLoading = false;
              this.addFormVisible = false;
              this.$message({
                message: res.data.Message,
                type: "success",
              });
              this.$refs["addForm"].resetFields();
              // this.$refs.table.setCurrentRow();
       
              this.getMenus();
              this.initMenuTree();
            } else {
              this.$message({
                message: res.data.message,
                type: "error",
              });
            }
          });
        }
      });
    },
    initFunction: function () {
      if (this.functions.length == 0) {
        getFunctionAll().then((res) => {
          if (res.IsSuccess) {
            this.functions = res.Data;
          }
        });
      }
      if (this.apilist.length == 0) {
        GetApiListEnabled().then((res) => {
          this.apilist = res.Data;
        });
      }
      if (this.menuOptions.length == 0) {
        this.initMenuTree();
      }
    },
    initMenuTree: function () {
      getMenuTree({}).then((res) => {
        this.menuOptions = [];
        this.menuOptions.push(res.Data);
        this.addLoading = false;
      });
    },
  },
  mounted() {
    this.getMenus();
    this.initFunction();

   // this.searchVisible=false;
    let routers = window.localStorage.router
      ? JSON.parse(window.localStorage.router)
      : [];
    this.buttonList = getButtonList(this.$route.path, routers);
  },
};
</script>

<style scoped>
</style>
